from pages.base_page import BasePage
from utils.exception_handler import SmartExceptionHandler

class LoginPage(BasePage):
    def __init__(self, test_case):
        """初始化，接受 test_case"""
        super().__init__(test_case)
        self.elements = self.load_elements("login_page")

    def open_login_page(self):
        """打开登录页面"""
        self.test_case.open(f"{self.config['production_base_url']}")
        self.test_case.wait_for_element(self.elements["username_field"])
        return self
    
    @SmartExceptionHandler.retry_on_failure
    def enter_username(self, username):
        """输入用户名"""
        self.update_input(self.elements["username_field"], username)
        return self
    
    @SmartExceptionHandler.retry_on_failure
    def enter_password(self, password):
        """输入密码"""
        self.update_input(self.elements["password_field"], password, sensitive=True)
        return self
    
    @SmartExceptionHandler.retry_on_failure
    def click_login(self):
        """点击登录按钮"""
        self.test_case.click(self.elements["login_button"])
        return self
    @SmartExceptionHandler.retry_on_failure
    def is_login_successful(self):
        """检查登录是否成功"""
        self.test_case.sleep(2)
        self.test_case.assert_text("欢迎")
    
    def login(self, username, password):
        """完整登录流程"""
        self.open_login_page()
        return (
            self.enter_username(username)
            .enter_password(password)
            .click_login()
            .is_login_successful()
        )
    
